package net.heri.xmppchat.activities.contactlist;

import java.util.ArrayList;

import com.google.inject.Inject;

import android.widget.Filter;

public class ContactListFilter extends Filter {
	
	private ContactListAdapter mAdapter;
	
	@Inject
	public ContactListFilter(ContactListAdapter adapter) {
		this.mAdapter = adapter;
	}
	
	@Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults Result = new FilterResults();
        // if constraint is empty return the original names
        if(constraint.length() == 0 ){
            Result.values = mAdapter.getContainerList();
            Result.count = mAdapter.getCount();
            return Result;
        }
        
        ArrayList<String> Filtered_Names = new ArrayList<String>();
        String filterString = constraint.toString().toLowerCase();
        String filterableString;
        
        for(int i = 0; i< mAdapter.getCount(); i++){
            filterableString = (String) mAdapter.getItem(i);
            if(filterableString.toLowerCase().contains(filterString) ) {
                Filtered_Names.add(filterableString);
            }
        }
        Result.values = Filtered_Names;
        Result.count = Filtered_Names.size();
        
        return Result;
    }
	
    @Override
    protected void publishResults(CharSequence constraint,FilterResults results) {
    	mAdapter.setDisplayList((ArrayList<String>) results.values);
    	mAdapter.notifyDataSetChanged();
    }
}
